package know.how.glutenfree;

import java.util.ArrayList;
import java.util.List;

import com.bappi.custom.activities.CustomActivity;
import com.bappi.custom.activities.CustomActivityGroup;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;

public class Tab1Activity1 extends CustomActivity {

	private ListView listView;
	private List<RestaurantItem> filteredListItems;
	private List<RestaurantItem> allListItems;
	private EfficientAdapter adapter;
	private AutoCompleteTextView searchView;

	private final OnSharedPreferenceChangeListener ospcl = new OnSharedPreferenceChangeListener() {

		public void onSharedPreferenceChanged(final SharedPreferences sp,
				String key) {
			try {
				if(TabsController.KEY_TAB_0_CLICKED.equals(key)){
					runOnUiThread(new Runnable() {
						public void run() {
							try {
								((CustomActivityGroup)getParent()).backTo(1);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	public void onCreate(Bundle icicle) {
		try {
			super.onCreate(icicle);
			setContentView(R.layout.layout_tab_1_screen_1);
			filteredListItems = new ArrayList<RestaurantItem>();
			listView = (ListView) findViewById(R.id.list_view);
			searchView = (AutoCompleteTextView) findViewById(R.id.editText1);
			listView.setDividerHeight(0);
			allListItems = TabsController.getAllRestaurents();
			
//			List<String> names = new ArrayList<String>();
//			for(int i=0;i<allListItems.size();i++){
//				names.add(allListItems.get(i).getTitle());
//			}
//			ArrayAdapter<String> adap = 
//		            new ArrayAdapter<String>(getParent(), android.R.layout.simple_list_item_1,names);
//			searchView.setAdapter(adap);
			
			adapter = new EfficientAdapter(this);
			listView.setAdapter(adapter);

			
			searchView.addTextChangedListener(new TextWatcher() {

				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					try {
						showFiltering();
					} catch (Exception e) {
						e.printStackTrace();
					}
					
				}

				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					// TODO Auto-generated method stub

				}

				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub

				}
			});
			showFiltering();
			TabsController.getSharedPreferences().registerOnSharedPreferenceChangeListener(ospcl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onDestroy() {
		try {
			TabsController.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(ospcl);
		} catch (Exception e) {
			// TODO: handle exception
		}
		super.onDestroy();
	}

	private void showFiltering(){
		try {
			String key = searchView.getText().toString().toLowerCase();
			filteredListItems.clear();
			if(key.length()>0){
				RestaurantItem listItem;
				for (int i = 0; i < allListItems.size(); i++) {
					listItem = allListItems.get(i);
					if (listItem.getTitle().toLowerCase().contains(key)) {
						filteredListItems.add(listItem);
					}
				}
			}else{
				filteredListItems.addAll(allListItems);
			}
			adapter.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	private void hideKeyboard(){
		try {
			View view = getCurrentFocus();
			if(view!=null){
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public EfficientAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			try {
				ViewHolder holder;
				if (convertView == null) {
					convertView = mInflater
							.inflate(R.layout.restaurant_list_content, null);
					holder = new ViewHolder();
					holder.mainContainer = convertView
							.findViewById(R.id.main_container);
					holder.button = (Button) convertView
							.findViewById(R.id.button);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				Drawable drawable = getResources().getDrawable(
						getResources().getIdentifier(
								filteredListItems.get(position)
										.getDrawableName(), "drawable",
								getClass().getPackage().getName()));
				holder.button.setCompoundDrawablesWithIntrinsicBounds(drawable,
						null, null, null);
				holder.button.setText(filteredListItems.get(position)
						.getTitle());
				holder.button.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						hideKeyboard();
						final RestaurantItem listItem = filteredListItems
								.get(position);
						Intent intent = new Intent(getParent(),
								RestaurantDetailsActivity.class);
						intent.putExtra(RestaurantDetailsActivity.KEY_ID,
								listItem.getId());
						pushIntnet(intent);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHolder {
			View mainContainer;
			Button button;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public int getCount() {
			return filteredListItems.size();
		}

		public Object getItem(int position) {
			return filteredListItems.get(position);
		}
	}
}